<template>
  <div class="content-card">
    <div class="page-header">
      <h2>支付报表</h2>
      <el-button type="primary" @click="handleExport">导出报表</el-button>
    </div>
    
    <!-- 报表筛选条件 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式">
          <el-option label="全部" value="" />
          <el-option label="支付宝" value="1" />
          <el-option label="微信支付" value="2" />
          <el-option label="银行卡" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择支付状态">
          <el-option label="全部" value="" />
          <el-option label="支付成功" value="1" />
          <el-option label="支付失败" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 概览统计卡片 -->
    <div class="overview-cards">
      <div class="stat-card">
        <div class="stat-title">总交易金额</div>
        <div class="stat-value total-amount">{{ formatPrice(totalAmount) }}</div>
        <div class="stat-change" :class="{ positive: dailyChangeRate > 0, negative: dailyChangeRate < 0 }">
          较昨日 {{ dailyChangeRate > 0 ? '+' : '' }}{{ dailyChangeRate }}%
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总交易笔数</div>
        <div class="stat-value total-count">{{ totalCount }}</div>
        <div class="stat-change" :class="{ positive: dailyCountChange > 0, negative: dailyCountChange < 0 }">
          较昨日 {{ dailyCountChange > 0 ? '+' : '' }}{{ dailyCountChange }}%
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">成功交易笔数</div>
        <div class="stat-value success-count">{{ successCount }}</div>
        <div class="stat-subtitle">成功率 {{ successRate }}%</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">平均客单价</div>
        <div class="stat-value avg-amount">{{ formatPrice(avgAmount) }}</div>
        <div class="stat-change" :class="{ positive: avgChangeRate > 0, negative: avgChangeRate < 0 }">
          较昨日 {{ avgChangeRate > 0 ? '+' : '' }}{{ avgChangeRate }}%
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 交易趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>交易趋势</h3>
          <el-radio-group v-model="trendChartType" @change="handleTrendChartTypeChange">
            <el-radio-button label="amount">金额</el-radio-button>
            <el-radio-button label="count">笔数</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-content">
          <div ref="trendChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 支付方式分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>支付方式分布</h3>
          <el-radio-group v-model="paymentMethodChartType" @change="handlePaymentMethodChartTypeChange">
            <el-radio-button label="amount">金额占比</el-radio-button>
            <el-radio-button label="count">笔数占比</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-content">
          <div ref="paymentMethodChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 时段分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>交易时段分布</h3>
        </div>
        <div class="chart-content">
          <div ref="timeDistributionChart" class="chart"></div>
        </div>
      </div>
      
      <!-- 区域分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>区域交易分布</h3>
        </div>
        <div class="chart-content">
          <div ref="areaDistributionChart" class="chart"></div>
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <h3>交易明细数据</h3>
      <el-table 
        v-loading="loading" 
        :data="detailList" 
        style="width: 100%"
      >
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="totalAmount" label="交易金额" width="120" formatter="formatPrice" />
        <el-table-column prop="totalCount" label="交易笔数" width="100" />
        <el-table-column prop="successCount" label="成功笔数" width="100" />
        <el-table-column prop="successRate" label="成功率" width="100" formatter="formatRate" />
        <el-table-column prop="avgAmount" label="平均客单价" width="120" formatter="formatPrice" />
        <el-table-column prop="refundAmount" label="退款金额" width="100" formatter="formatPrice" />
      </el-table>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { paymentApi } from '../../api/payment.js'
// 引入ECharts
import * as echarts from 'echarts'

export default {
  name: 'PaymentReport',
  setup() {
    const loading = ref(false)
    
    // 搜索表单
    const searchForm = reactive({
      timeRange: [],
      paymentMethod: '',
      status: ''
    })
    
    // 统计数据
    const totalAmount = ref(0)
    const totalCount = ref(0)
    const successCount = ref(0)
    const successRate = ref(0)
    const avgAmount = ref(0)
    const dailyChangeRate = ref(0)
    const dailyCountChange = ref(0)
    const avgChangeRate = ref(0)
    
    // 图表类型
    const trendChartType = ref('amount')
    const paymentMethodChartType = ref('amount')
    
    // 图表实例
    const trendChart = ref(null)
    const paymentMethodChart = ref(null)
    const timeDistributionChart = ref(null)
    const areaDistributionChart = ref(null)
    
    // 图表实例引用
    let trendChartInstance = null
    let paymentMethodChartInstance = null
    let timeDistributionChartInstance = null
    let areaDistributionChartInstance = null
    
    // 明细数据
    const detailList = ref([])
    
    // 格式化价格
    const formatPrice = (value) => {
      return `¥${Number(value).toFixed(2)}`
    }
    
    // 格式化百分比
    const formatRate = (row, column, cellValue) => {
      return `${Number(cellValue).toFixed(2)}%`
    }
    
    // 获取报表数据
    const getReportData = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          startDate: searchForm.timeRange[0] || '',
          endDate: searchForm.timeRange[1] || ''
        }
        
        // 移除数组形式的时间范围，只保留开始和结束日期
        delete params.timeRange
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          // 生成随机统计数据
          const mockStats = generateMockStats()
          totalAmount.value = mockStats.totalAmount
          totalCount.value = mockStats.totalCount
          successCount.value = mockStats.successCount
          successRate.value = mockStats.successRate
          avgAmount.value = mockStats.avgAmount
          dailyChangeRate.value = mockStats.dailyChangeRate
          dailyCountChange.value = mockStats.dailyCountChange
          avgChangeRate.value = mockStats.avgChangeRate
          
          // 生成明细数据
          detailList.value = generateDetailList()
          
          // 渲染图表
          nextTick(() => {
            renderCharts()
          })
          
          loading.value = false
        }, 800)
        
        // 实际API调用代码（目前注释掉）
        // const response = await paymentApi.getPaymentReport(params)
        // const data = response.data
        // totalAmount.value = data.totalAmount
        // totalCount.value = data.totalCount
        // successCount.value = data.successCount
        // successRate.value = data.successRate
        // avgAmount.value = data.avgAmount
        // dailyChangeRate.value = data.dailyChangeRate
        // dailyCountChange.value = data.dailyCountChange
        // avgChangeRate.value = data.avgChangeRate
        // detailList.value = data.detailList
        // 
        // nextTick(() => {
        //   renderCharts()
        // })
        // loading.value = false
      } catch (error) {
        console.error('获取报表数据失败:', error)
        ElMessage.error('获取报表数据失败')
        loading.value = false
      }
    }
    
    // 生成模拟统计数据
    const generateMockStats = () => {
      const baseAmount = Math.floor(Math.random() * 500000) + 100000
      const baseCount = Math.floor(Math.random() * 5000) + 1000
      const successRatio = Math.random() * 0.05 + 0.95 // 95% - 100%成功率
      
      return {
        totalAmount: baseAmount,
        totalCount: baseCount,
        successCount: Math.floor(baseCount * successRatio),
        successRate: (successRatio * 100).toFixed(2),
        avgAmount: baseAmount / baseCount,
        dailyChangeRate: (Math.random() * 20 - 5).toFixed(2), // -5% to 15%
        dailyCountChange: (Math.random() * 25 - 5).toFixed(2), // -5% to 20%
        avgChangeRate: (Math.random() * 10 - 2).toFixed(2) // -2% to 8%
      }
    }
    
    // 生成明细数据
    const generateDetailList = () => {
      const list = []
      const days = 7 // 生成7天的数据
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
        
        // 基础数据，逐渐递增
        const baseAmount = 50000 + Math.floor(Math.random() * 50000) + (i * 5000)
        const baseCount = 300 + Math.floor(Math.random() * 200) + (i * 20)
        const successRatio = Math.random() * 0.03 + 0.97 // 97% - 100%成功率
        const refundRatio = Math.random() * 0.02 // 0% - 2%退款率
        
        list.push({
          date: dateStr,
          totalAmount: baseAmount,
          totalCount: baseCount,
          successCount: Math.floor(baseCount * successRatio),
          successRate: (successRatio * 100).toFixed(2),
          avgAmount: baseAmount / baseCount,
          refundAmount: Math.floor(baseAmount * refundRatio)
        })
      }
      
      return list
    }
    
    // 渲染所有图表
    const renderCharts = () => {
      renderTrendChart()
      renderPaymentMethodChart()
      renderTimeDistributionChart()
      renderAreaDistributionChart()
    }
    
    // 渲染交易趋势图
    const renderTrendChart = () => {
      if (!trendChart.value) return
      
      if (trendChartInstance) {
        trendChartInstance.dispose()
      }
      
      trendChartInstance = echarts.init(trendChart.value)
      
      const dates = detailList.value.map(item => item.date)
      const amounts = detailList.value.map(item => item.totalAmount)
      const counts = detailList.value.map(item => item.totalCount)
      
      const option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let result = `${params[0].axisValue}<br/>`
            params.forEach(param => {
              const value = trendChartType.value === 'amount' 
                ? `¥${param.value.toFixed(2)}` 
                : param.value
              result += `${param.marker} ${param.seriesName}: ${value}<br/>`
            })
            return result
          }
        },
        legend: {
          data: [trendChartType.value === 'amount' ? '交易金额' : '交易笔数'],
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => {
              if (trendChartType.value === 'amount') {
                if (value >= 10000) {
                  return `${(value / 10000).toFixed(1)}w`
                }
                return value
              }
              return value
            }
          }
        },
        series: [{
          name: trendChartType.value === 'amount' ? '交易金额' : '交易笔数',
          type: 'line',
          smooth: true,
          data: trendChartType.value === 'amount' ? amounts : counts,
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          }
        }]
      }
      
      trendChartInstance.setOption(option)
    }
    
    // 渲染支付方式分布图表
    const renderPaymentMethodChart = () => {
      if (!paymentMethodChart.value) return
      
      if (paymentMethodChartInstance) {
        paymentMethodChartInstance.dispose()
      }
      
      paymentMethodChartInstance = echarts.init(paymentMethodChart.value)
      
      // 模拟支付方式分布数据
      const paymentMethods = [
        { name: '支付宝', value: paymentMethodChartType.value === 'amount' ? 520000 : 3200 },
        { name: '微信支付', value: paymentMethodChartType.value === 'amount' ? 380000 : 2800 },
        { name: '银行卡', value: paymentMethodChartType.value === 'amount' ? 100000 : 1000 }
      ]
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: paymentMethods.map(item => item.name)
        },
        series: [{
          name: '支付方式',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['60%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: paymentMethods
        }]
      }
      
      paymentMethodChartInstance.setOption(option)
    }
    
    // 渲染时段分布图表
    const renderTimeDistributionChart = () => {
      if (!timeDistributionChart.value) return
      
      if (timeDistributionChartInstance) {
        timeDistributionChartInstance.dispose()
      }
      
      timeDistributionChartInstance = echarts.init(timeDistributionChart.value)
      
      // 模拟时段分布数据
      const timeSlots = ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
      const values = [
        Math.floor(Math.random() * 10000) + 5000,
        Math.floor(Math.random() * 5000) + 2000,
        Math.floor(Math.random() * 8000) + 5000,
        Math.floor(Math.random() * 20000) + 10000,
        Math.floor(Math.random() * 25000) + 15000,
        Math.floor(Math.random() * 30000) + 20000,
        Math.floor(Math.random() * 35000) + 25000,
        Math.floor(Math.random() * 25000) + 15000
      ]
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            return `${params[0].axisValue}<br/>${params[0].marker} 交易金额: ¥${params[0].value.toFixed(2)}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timeSlots
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => {
              if (value >= 10000) {
                return `${(value / 10000).toFixed(1)}w`
              }
              return value
            }
          }
        },
        series: [{
          data: values,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#67c23a' },
              { offset: 1, color: '#85ce61' }
            ])
          }
        }]
      }
      
      timeDistributionChartInstance.setOption(option)
    }
    
    // 渲染区域分布图表
    const renderAreaDistributionChart = () => {
      if (!areaDistributionChart.value) return
      
      if (areaDistributionChartInstance) {
        areaDistributionChartInstance.dispose()
      }
      
      areaDistributionChartInstance = echarts.init(areaDistributionChart.value)
      
      // 模拟区域分布数据
      const areas = ['华东', '华北', '华南', '西南', '西北', '东北', '华中']
      const values = areas.map(() => Math.floor(Math.random() * 200000) + 50000)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            return `${params[0].axisValue}<br/>${params[0].marker} 交易金额: ¥${params[0].value.toFixed(2)}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => {
              if (value >= 10000) {
                return `${(value / 10000).toFixed(1)}w`
              }
              return value
            }
          }
        },
        yAxis: {
          type: 'category',
          data: areas
        },
        series: [{
          data: values,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: '#e6a23c' },
              { offset: 1, color: '#ebb563' }
            ])
          }
        }]
      }
      
      areaDistributionChartInstance.setOption(option)
    }
    
    // 处理搜索
    const handleSearch = () => {
      if (!searchForm.timeRange || searchForm.timeRange.length < 2) {
        ElMessage.warning('请选择时间范围')
        return
      }
      getReportData()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'timeRange') {
          searchForm[key] = []
        } else {
          searchForm[key] = ''
        }
      })
    }
    
    // 处理交易趋势图表类型变化
    const handleTrendChartTypeChange = () => {
      renderTrendChart()
    }
    
    // 处理支付方式图表类型变化
    const handlePaymentMethodChartTypeChange = () => {
      renderPaymentMethodChart()
    }
    
    // 处理导出报表
    const handleExport = async () => {
      try {
        if (!searchForm.timeRange || searchForm.timeRange.length < 2) {
          ElMessage.warning('请选择时间范围')
          return
        }
        
        // 模拟导出请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success('报表导出成功')
          loading.value = false
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // const params = {
        //   ...searchForm,
        //   startDate: searchForm.timeRange[0],
        //   endDate: searchForm.timeRange[1]
        // }
        // delete params.timeRange
        // await paymentApi.exportPaymentReport(params)
        // ElMessage.success('报表导出成功')
      } catch (error) {
        console.error('导出报表失败:', error)
        ElMessage.error('导出报表失败')
        loading.value = false
      }
    }
    
    // 处理窗口大小变化，重新调整图表大小
    const handleResize = () => {
      if (trendChartInstance) trendChartInstance.resize()
      if (paymentMethodChartInstance) paymentMethodChartInstance.resize()
      if (timeDistributionChartInstance) timeDistributionChartInstance.resize()
      if (areaDistributionChartInstance) areaDistributionChartInstance.resize()
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      // 默认设置时间范围为最近7天
      const endDate = new Date()
      const startDate = new Date()
      startDate.setDate(startDate.getDate() - 7)
      searchForm.timeRange = [
        `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(startDate.getDate()).padStart(2, '0')}`,
        `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')}`
      ]
      
      // 获取报表数据
      getReportData()
      
      // 添加窗口大小变化监听
      window.addEventListener('resize', handleResize)
    })
    
    // 组件卸载时清理
    onUnmounted(() => {
      // 销毁图表实例
      if (trendChartInstance) trendChartInstance.dispose()
      if (paymentMethodChartInstance) paymentMethodChartInstance.dispose()
      if (timeDistributionChartInstance) timeDistributionChartInstance.dispose()
      if (areaDistributionChartInstance) areaDistributionChartInstance.dispose()
      
      // 移除窗口大小变化监听
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      loading,
      searchForm,
      totalAmount,
      totalCount,
      successCount,
      successRate,
      avgAmount,
      dailyChangeRate,
      dailyCountChange,
      avgChangeRate,
      trendChartType,
      paymentMethodChartType,
      trendChart,
      paymentMethodChart,
      timeDistributionChart,
      areaDistributionChart,
      detailList,
      formatPrice,
      formatRate,
      handleSearch,
      handleReset,
      handleTrendChartTypeChange,
      handlePaymentMethodChartTypeChange,
      handleExport
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 15px;
  }
}

.overview-cards {
  display: flex;
  margin-bottom: 20px;
  
  .stat-card {
    flex: 1;
    background-color: #f9f9f9;
    border-radius: 4px;
    padding: 20px;
    margin-right: 20px;
    text-align: center;
    
    &:last-child {
      margin-right: 0;
    }
    
    .stat-title {
      color: var(--text-secondary);
      font-size: 14px;
      margin-bottom: 10px;
    }
    
    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 5px;
      
      &.total-amount {
        color: #409eff;
      }
      
      &.total-count {
        color: #67c23a;
      }
      
      &.success-count {
        color: #e6a23c;
      }
      
      &.avg-amount {
        color: #f56c6c;
      }
    }
    
    .stat-change {
      font-size: 12px;
      
      &.positive {
        color: #67c23a;
      }
      
      &.negative {
        color: #f56c6c;
      }
    }
    
    .stat-subtitle {
      font-size: 12px;
      color: var(--text-secondary);
    }
  }
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
  margin-bottom: 20px;
  
  .chart-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .chart-content {
      padding: 20px;
      
      .chart {
        width: 100%;
        height: 300px;
      }
    }
  }
}

.table-section {
  margin-top: 30px;
  
  h3 {
    margin-bottom: 15px;
    font-size: 16px;
    font-weight: 500;
  }
}
</style>